package com.enation.app.shop.front.api.appcontroller;

import com.enation.app.base.core.model.Member;
import com.enation.app.shop.core.goods.service.IGoodsManager;
import com.enation.app.shop.core.member.model.Favorite;
import com.enation.app.shop.core.member.service.IFavoriteManager;
import com.enation.app.shop.core.member.service.IMemberCommentManager;
import com.enation.eop.sdk.context.UserConext;
import com.enation.eop.sdk.utils.StaticResourcesUtil;
import com.enation.framework.action.JsonResult;
import com.enation.framework.util.JsonResultUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收藏的类
 */
@Scope("prototype")
@Controller
@RequestMapping("/app/collect")
public class CollectAppController {
    @Autowired
    private IFavoriteManager favoriteManager;
    @Autowired
    private IMemberCommentManager memberCommentManager;
    @Autowired
    private IGoodsManager goodsManager;


    /**
     * 收藏一个商品，必须登录才能调用此api
     * @param goods_id ：要收藏的商品id,int型
     * @return
     * @return 返回json串
     * result  为1表示调用成功0表示失败 ，int型
     * message 为提示信息
     */
    @ResponseBody
    @RequestMapping(value="/addcollect",produces = MediaType.APPLICATION_JSON_VALUE)
    public JsonResult addCollect(Integer goods_id,Integer userid){
        if(userid!=null){
            int count = favoriteManager.getCount(goods_id,userid);
            if (count == 0){
                favoriteManager.add(goods_id,userid);
                return JsonResultUtil.getSuccessJson("添加收藏成功");
            }else{
                return JsonResultUtil.getErrorJson("已收藏该商品");
            }
        }else{
            return JsonResultUtil.getErrorJson("对不起，请您登录后再收藏该商品！");
        }
    }

    /**
     * 取消收藏
     * @param goods_id
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/cancelcollect",produces = MediaType.APPLICATION_JSON_VALUE)
    public JsonResult cancelCollect(Integer goods_id,Integer userid){
        try {
            if (userid != null) {
                //增加操作权限校验
                Favorite favorite=favoriteManager.get(goods_id,userid);
                if(favorite==null || !userid.equals(favorite.getMember_id())){
                    return JsonResultUtil.getSuccessJson("您没有操作权限");
                }
                this.favoriteManager.cancel(goods_id,userid);
                return JsonResultUtil.getSuccessJson("删除成功");
            }else{
                return JsonResultUtil.getErrorJson("请先登录");
            }
        } catch (Exception e) {
            Logger logger = Logger.getLogger(getClass());
            if (logger.isDebugEnabled()) {
                logger.error(e.getStackTrace());
            }
            return JsonResultUtil.getErrorJson("删除失败[" + e.getMessage() + "]");
        }
    }


    /**
     * 取消一个商品的收藏，必须登录才能调用此api
     * @param favorite_id ：收藏id，即Favorite.favorite_id
     * @return
     * @return 返回json串
     * result  为1表示调用成功0表示失败 ，int型
     * message 为提示信息
     *
     * {@link Favorite}
     */
    @ResponseBody
    @RequestMapping(value="/cancelcollec",produces = MediaType.APPLICATION_JSON_VALUE)
    public JsonResult cancelCollec(Integer favorite_id,Integer userid){
        try {
            if (userid != null) {
                //增加操作权限校验
                Favorite favorite = favoriteManager.get(favorite_id);
                if(favorite==null || !userid.equals(favorite.getMember_id())){
                    return JsonResultUtil.getSuccessJson("您没有操作权限");
                }
                this.favoriteManager.delete(favorite_id);
                return JsonResultUtil.getSuccessJson("删除成功");
            }else{
                return JsonResultUtil.getErrorJson("请先登录");
            }
        } catch (Exception e) {
            Logger logger = Logger.getLogger(getClass());
            if (logger.isDebugEnabled()) {
                logger.error(e.getStackTrace());
            }
            return JsonResultUtil.getErrorJson("删除失败[" + e.getMessage() + "]");
        }
    }
    /**
     * 删除一个会员收藏  whj 0225 下午18：25
     * @param favorite_id ：要删除的会员收藏地址id,String型
     * result  为1表示添加成功，0表示失败 ，int型
     * message 为提示信息 ，String型
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/delete",produces = MediaType.APPLICATION_JSON_VALUE)
    public JsonResult delete(Integer favorite_id) {
        try {
            Member member = UserConext.getCurrentMember();
            if (member != null) {
                //增加操作权限校验
                Favorite favorite = favoriteManager.get(favorite_id);
                if(favorite==null || !member.getMember_id().equals(favorite.getMember_id())){
                    return JsonResultUtil.getSuccessJson("您没有操作权限");
                }
                this.favoriteManager.delete(favorite_id);
                return JsonResultUtil.getSuccessJson("删除成功");
            }else{
                return JsonResultUtil.getErrorJson("请先登录");
            }
        } catch (Exception e) {
            Logger logger = Logger.getLogger(getClass());
            if (logger.isDebugEnabled()) {
                logger.error(e.getStackTrace());
            }
            return JsonResultUtil.getErrorJson("删除失败[" + e.getMessage() + "]");
        }
    }


    /**
     *
     *   //得到收藏列表userid前台传过来
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("/getusercollect")
    public  JsonResult getUserCollect(int userid) {
        List<Map<String, Object>>  goods= favoriteManager.getMyCollectByuserid(userid);
       List<Map<String,Object>>  goodsSmall = new ArrayList<Map<String, Object>>();
        for (Map<String,Object> good:goods){
            Map<String,Object> goodsSmalls=new HashMap<String,Object>();
            goodsSmalls.put("goodsid", good.get("goods_id"));
            goodsSmalls.put("price", good.get("price"));
            goodsSmalls.put("name", good.get("name"));
            goodsSmalls.put("thum", StaticResourcesUtil.transformPathapp(good.get("thumbnail").toString()));
            goodsSmalls.put("buycount",good.get("buy_count"));
            goodsSmalls.put("favid",good.get("favorite_id"));
            int goodsid = Integer.parseInt(good.get("goods_id").toString());
            int count = memberCommentManager.getCommentsCount(goodsid);
            int count3 = memberCommentManager.getCommentsGradeCount(goodsid, 3);//好评数量
            if (count == 0) {
                goodsSmalls.put("sup", "100%");
            } else {
                DecimalFormat df = new DecimalFormat("0.00%");
                float ab=(float) count3/count;
                goodsSmalls.put("sup", df.format(ab));
            }
           int typeid= Integer.parseInt(goodsManager.get(goodsid).get("type_id").toString());
            if (typeid==64){
                goodsSmalls.put("productTypes",0);
            }else if (typeid==65){
                goodsSmalls.put("productTypes",1);
            }else {
                goodsSmalls.put("productTypes",2);
            }
            goodsSmall.add(goodsSmalls);
       }
        return JsonResultUtil.getObjectMessageJson(goodsSmall, "得到收藏列表userid前台传过来");
    }


    /**
     * //得到当前登录人的收藏总数
     * @param userid
     * @return
     */
    @ResponseBody
    @RequestMapping("getcollectcount")
    public int getusercollectcount(int userid){
        int collectcount=favoriteManager.getCount(userid);
        return  collectcount;
    }




}
